﻿using Helpers;
using Helpers.Common;
using Helpers.Log;
using log4net;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace RemoteControl.Service.Wcf
{
    [ServiceBehavior(IncludeExceptionDetailInFaults = true, InstanceContextMode = InstanceContextMode.Single)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class RemoteControlWcfService : IRemoteControlWcfService
    {
        #region Properties


        #endregion

        #region Fields

        /// <summary>
        /// A <typeparamref name="log4net.ILog"/> object.
        /// </summary>
        private ILog logger = Helpers.Log.Logger.GetLogger(MethodBase.GetCurrentMethod().DeclaringType.Name);

        #endregion

        #region Constructor

        public RemoteControlWcfService()
        {
        }

        #endregion

        #region Wcf Methods

        public Response<string> PressKey(string key)
        {
            TransactionLogger tranLog = new TransactionLogger(this.logger, MethodBase.GetCurrentMethod().Name);
            Response<string> response = null;
            try
            {
                tranLog.ParametersCollection = new Dictionary<string, object>
                {
                    { "key", key },
                };

                //Log begin of the transaction.
                tranLog.LogBegin();


                Process proc = Processes.GetActiveWindowProcess();

                this.SendKey(key, proc);


                response = new Response<string>();


                //Log successful end of the transaction.
                tranLog.LogEnd();
            }
            catch (Exception ex)
            {
                string errorMsg = "Failed when trying to generate monthly report.";

                response = new Response<string>(ex, errorMsg);

                //Log end of the transaction with exception.
                tranLog.LogEnd(ex, errorMsg);
            }
            return response;
        }

        #endregion

        #region Common Methods

        private void SendKey(string key, Process proc)
        {
            IntPtr hWnd = proc.MainWindowHandle;

            /* Set as active the window of the tv program. */
            Processes.SetForegroundWindow(hWnd);

            /* Send key to application. */
            SendKeys.SendWait(key);
        }

        #endregion
    }
}